<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Nibbles in Tkinter</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="GUI, Nibbles, Python, Game, Tkinter, programming, Linux">
<meta name="description" content="This part of the Tkinter tutorial presents a Nibbles game clone.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Nibbles</h1>

<p>
In this part of the Tkinter tutorial, we will create a Nibbles game clone.
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
<b>Nibbles</b> is an older classic video game. It was first created in late 70s.
Later it was brought to PCs. In this game the player controls a snake.
The objective is to eat as many apples as possible. Each time the snake eats an apple,
its body grows. The snake must avoid the walls and its own body. 
</p>


<h2>Development</h2>

<p>
The size of each of the joints of a snake is 10px. The snake is controlled with 
the cursor keys. Initially, the snake has three joints. 
The game starts immediately. When the game is finished, 
we display "Game Over" message in the center of the window.
</p>

<p>
We use the <code>Canvas</code> widget to create the game. The objects in the
game are images. We use canvas methods to create image items. We use canvas methods to find 
items on the canvas using tags and to do collision detection.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode Tkinter tutorial 

This is a simple Nibbles game
clone.

author: Jan Bodnar
website: zetcode.com 
last edited: January 2011
"""


import sys
import random
from PIL import Image, ImageTk
from Tkinter import Tk, Frame, Canvas, ALL, NW


WIDTH = 300
HEIGHT = 300
DELAY = 100
DOT_SIZE = 10
ALL_DOTS = WIDTH * HEIGHT / (DOT_SIZE * DOT_SIZE)
RAND_POS = 27

x = [0] * ALL_DOTS
y = [0] * ALL_DOTS


class Board(Canvas):

    def __init__(self, parent):
        Canvas.__init__(self, width=WIDTH, height=HEIGHT, 
            background="black", highlightthickness=0)
         
        self.parent = parent 
        self.initGame()
        self.pack()
                       
    
    def initGame(self):

        self.left = False
        self.right = True
        self.up = False
        self.down = False
        self.inGame = True
        self.dots = 3
        
        self.apple_x = 100
        self.apple_y = 190

        for i in range(self.dots):
            x[i] = 50 - i * 10
            y[i] = 50
        
        try:
            self.idot = Image.open("dot.png")
            self.dot = ImageTk.PhotoImage(self.idot)    
            self.ihead = Image.open("head.png")
            self.head = ImageTk.PhotoImage(self.ihead)           
            self.iapple = Image.open("apple.png")
            self.apple = ImageTk.PhotoImage(self.iapple) 

        except IOError, e:
            print e
            sys.exit(1)

        self.focus_get()

        self.createObjects()
        self.locateApple()
        self.bind_all("&lt;Key&gt;", self.onKeyPressed)
        self.after(DELAY, self.onTimer)
        

    def createObjects(self):
    
        self.create_image(self.apple_x, self.apple_y, image=self.apple,
            anchor=NW, tag="apple")
        self.create_image(50, 50, image=self.head, anchor=NW,  tag="head")
        self.create_image(30, 50, image=self.dot, anchor=NW, tag="dot")
        self.create_image(40, 50, image=self.dot, anchor=NW, tag="dot")
   

    def checkApple(self):

        apple = self.find_withtag("apple")
        head = self.find_withtag("head")
        
        x1, y1, x2, y2 = self.bbox(head)
        overlap = self.find_overlapping(x1, y1, x2, y2)
            
        for ovr in overlap:
          
            if apple[0] == ovr:
                
                x, y = self.coords(apple)
                self.create_image(x, y, image=self.dot, anchor=NW, tag="dot")
                self.locateApple()
        
    
    def doMove(self):
      
        dots = self.find_withtag("dot")
        head = self.find_withtag("head")
                
        items = dots + head
        
        z = 0
        while z < len(items)-1:
            c1 = self.coords(items[z])
            c2 = self.coords(items[z+1])
            self.move(items[z], c2[0]-c1[0], c2[1]-c1[1])
            z += 1

        if self.left:
            self.move(head, -DOT_SIZE, 0)
            
        if self.right: 
            self.move(head, DOT_SIZE, 0)

        if self.up:
            self.move(head, 0, -DOT_SIZE)

        if self.down:
            self.move(head, 0, DOT_SIZE)
            

    def checkCollisions(self):

        dots = self.find_withtag("dot")
        head = self.find_withtag("head")
        
        x1, y1, x2, y2 = self.bbox(head)
        overlap = self.find_overlapping(x1, y1, x2, y2)
        
        for dot in dots:
            for over in overlap:
                if over == dot:
                  self.inGame = False
            
        if x1 < 0:
            self.inGame = False
        
        if x1 > WIDTH - DOT_SIZE:
            self.inGame = False

        if y1 < 0:
            self.inGame = False
        
        if y1 > HEIGHT - DOT_SIZE:
            self.inGame = False
        

    def locateApple(self):
    
        apple = self.find_withtag("apple")
        self.delete(apple[0])
    
        r = random.randint(0, RAND_POS)
        self.apple_x = r * DOT_SIZE
        r = random.randint(0, RAND_POS)
        self.apple_y = r * DOT_SIZE
        
        self.create_image(self.apple_x, self.apple_y, anchor=NW,
            image=self.apple, tag="apple")
                
   
    def onKeyPressed(self, e): 
    
        key = e.keysym

        if key == "Left" and not self.right: 
            self.left = True
            self.up = False
            self.down = False
        

        if key == "Right" and not self.left:
            self.right = True
            self.up = False
            self.down = False
        

        if key == "Up" and not self.down:
            self.up = True
            self.right = False
            self.left = False
        

        if key == "Down" and not self.up: 
            self.down = True
            self.right = False
            self.left = False
            
            
    def onTimer(self):

        if self.inGame:
            self.checkCollisions()
            self.checkApple()
            self.doMove()
            self.after(DELAY, self.onTimer)
        else:
            self.gameOver()            
            
             
    def gameOver(self):

        self.delete(ALL)
        self.create_text(self.winfo_width()/2, self.winfo_height()/2, 
            text="Game Over", fill="white")            


class Nibbles(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
                
        parent.title('Nibbles')
        self.board = Board(parent)
        self.pack()


def main():

    root = Tk()
    nib = Nibbles(root)
    root.mainloop()  


if __name__ == '__main__':
    main()
</pre>

<p>
First we will define some constants used in our game. 
</p>

<p>
The <code>WIDTH</code> and <code>HEIGHT</code> constants determine 
the size of the Board. The <code>DELAY</code> constant determines the speed of the game.
The <code>DOT_SIZE</code> is the size of the apple and the dot
of the snake. The <code>ALL_DOTS</code> constant defines the maximum number of 
possible dots on the Board. The <code>RAND_POS</code> constant is used to calculate 
a random position of an apple. 
</p>

<pre class="explanation">
x = [0] * ALL_DOTS
y = [0] * ALL_DOTS
</pre>

<p>
These two arrays store x, y coordinates of all possible joints of a snake. 
</p>

<p>
The <code>initGame()</code> method initializes variables, loads 
images and starts a timeout function.
</p>

<pre class="explanation">
try:
    self.idot = Image.open("dot.png")
    self.dot = ImageTk.PhotoImage(self.idot)    
    self.ihead = Image.open("head.png")
    self.head = ImageTk.PhotoImage(self.ihead)           
    self.iapple = Image.open("apple.png")
    self.apple = ImageTk.PhotoImage(self.iapple) 

except IOError, e:
    print e
    sys.exit(1)
</pre>

<p>
In these lines, we load our images. There are three images in the Nibbles game.
The head, the dot and the apple. 
</p>

<pre class="explanation">
self.createObjects()
self.locateApple()
</pre>

<p>
The createObjects() method creates items on the canvas. The locateApple() puts
an apple randomly on the canvas.
</p>

<pre class="explanation">
self.bind_all("&lt;Key&gt;", self.onKeyPressed)
</pre>

<p>
We bind the keyboard events to the onKeyPressed() method. The game is
controlled with keyboard cursor keys. 
</p>

<pre class="explanation">
def createObjects(self):

    self.create_image(self.apple_x, self.apple_y, image=self.apple,
        anchor=NW, tag="apple")
    self.create_image(50, 50, image=self.head, anchor=NW,  tag="head")
    self.create_image(30, 50, image=self.dot, anchor=NW, tag="dot")
    self.create_image(40, 50, image=self.dot, anchor=NW, tag="dot")
</pre>

<p>
In the createObjects() method, we create game objects on the canvas. 
These are canvas items. They are given initial x, y coordinates. The
<code>image</code> parameter provides the image to be displayed. The <code>anchor</code>
parameter is set to NW; this way the coordinates of the canvas item are the top-left points 
of the items. This is important if we want to be able to display images next
to the borders of the root window. If you don't know what I mean, try to delete the anchor 
parameter. The <code>tag</code> parameter is used to identify items on the canvas. 
One tag may be used for multiple canvas items.
</p>

<p>
The checkApple() method checks, if the snake has hit
the apple object. If so, we add another snake joint and call the 
locateApple().
</p>

<pre class="explanation">
apple = self.find_withtag("apple")
head = self.find_withtag("head")
</pre>

<p>
The <code>find_withtag()</code> method finds an item on the canvas
using its tag. We need two items. The head of the snake and the 
apple. Note that even if there is only one item with a given tag,
the method returns a tuple. This is a case for the apple item. And
later the apple item is accessed the following way: apple[0]. 
</p>

<pre class="explanation">
x1, y1, x2, y2 = self.bbox(head)
overlap = self.find_overlapping(x1, y1, x2, y2)
</pre>

<p>
The <code>bbox()</code> method returns the bounding box points of an
item. The <code>find_overlapping()</code> method finds colliding
items for the given coordinates. 
</p>

<pre class="explanation">
for ovr in overlap:
  
    if apple[0] == ovr:
        x, y = self.coords(apple)
        self.create_image(x, y, image=self.dot, anchor=NW, tag="dot")
        self.locateApple()
</pre>

<p>
If the apple collides with the head, we create a new dot item at
the coordinates of the apple object. We call the locateApple() method, 
which deletes the old apple item from the canvas and creates and randomly
positions a new one. 
</p>

<p>
In the doMove() method we have the key algorithm of the game. 
To understand it, look at how the snake is moving. You control the head of the snake. 
You can change its direction with the cursor keys. The rest of the joints move
one position up the chain. The second joint moves where the first was, 
the third joint where the second was etc. 
</p>

<pre class="explanation">
z = 0
while z < len(items)-1:
    c1 = self.coords(items[z])
    c2 = self.coords(items[z+1])
    self.move(items[z], c2[0]-c1[0], c2[1]-c1[1])
    z += 1
</pre>

<p>
This code moves the joints up the chain. 
</p>

<pre class="explanation">
if self.left:
    self.move(head, -DOT_SIZE, 0)
</pre>

<p>
Move the head to the left.
</p>

<p>
In the <code>checkCollisions()</code> method, we determine if the snake
has hit itself or one of the walls. 
</p>


<pre class="explanation">
x1, y1, x2, y2 = self.bbox(head)
overlap = self.find_overlapping(x1, y1, x2, y2)

for dot in dots:
    for over in overlap:
        if over == dot:
          self.inGame = False
</pre>

<p>
Finish the game, if the snake hits one of its joints with the head.
</p>

<pre class="explanation">
if y1 > HEIGHT - DOT_SIZE:
    self.inGame = False
</pre>

<p>
Finish the game, if the snake hits the bottom of the Board. 
</p>

<p>
The locateApple() method locates a new apple randomly 
on the board and deletes the old one.
</p>

<pre class="explanation">
apple = self.find_withtag("apple")
self.delete(apple[0])
</pre>

<p>
Here we find and delete the apple, that was eaten by the snake.
</p>


<pre class="explanation">
r = random.randint(0, RAND_POS)
</pre>

<p>
We get a random number from 0 to RAND_POS - 1. 
</p>

<pre class="explanation">
self.apple_x = r * DOT_SIZE
...
self.apple_y = r * DOT_SIZE
</pre>

<p>
These lines set the x, y coordinates of the apple
object. 
</p>

<p>
In the <code>onKeyPressed()</code> method of the Board class, we 
determine the keys that were pressed.
</p>

<pre class="explanation">
if key == "Left" and not self.right: 
    self.left = True
    self.up = False
    self.down = False
</pre>

<p>
If we hit the left cursor key, we set left variable to 
true. This variable is used in the doMove()
method to change coordinates of the snake object. Notice also, that
when the snake is heading to the right, we cannot turn immediately 
to the left. 
</p>


<pre class="explanation">
def onTimer(self):

    if self.inGame:
        self.checkCollisions()
        self.checkApple()
        self.doMove()
        self.after(DELAY, self.onTimer)
    else:
        self.gameOver() 
</pre>

<p>
Every DELAYms, the onTimer() method is called. If 
we are in the game, we call three methods, that build the logic of the game.
Otherwise the game is finished. The timer is based on the <code>after()</code> 
method, which calls a method after DELAYms only once. To repeteadly call the timer,
we recursively call the onTimer() method. 
</p>


<pre class="explanation">
def gameOver(self):

    self.delete(ALL)
    self.create_text(self.winfo_width()/2, self.winfo_height()/2, 
        text="Game Over", fill="white")     
</pre>

<p>
If the game is over, we delete all items on the canvas. Then we
draw "Game Over" in the center of the screen. 
</p>

<img src="/img/gui/tkinter/nibbles.png" alt="Nibbles">
<div class="figure">Figure: Nibbles</div>


<p>
This was the Nibbles computer game created with the Tkinter library.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 10, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

